package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value="sso_token", required = false) String sso_token){
        if(!StringUtils.isEmpty(sso_token)){
            //说明之前有人登录，浏览器有痕迹
            return "redirect:" + url + "?token=" + sso_token;
        }
        return "login";
    }
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam String username,
                          @RequestParam String password,
                          @RequestParam String redirect_url,
                          HttpServletResponse response){
        //登录成功需要跳转
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功
            String uuid = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(uuid, username);
            Cookie ssoToken = new Cookie("sso_token", uuid);
            response.addCookie(ssoToken);
            return "redirect:" + redirect_url + "?token=" + uuid;
        }
        //登陆失败展示登陆页面
        return "login";
    }
}
